import Flutter
import Foundation

/// 数据事件DataEventChannel管理器 - 专门处理持续数据流
/// 使用EventChannel实现，适合iOS端持续向Flutter发送数据
class DataEventChannel: NSObject {
    static let shared = DataEventChannel()

    private var eventChannel: FlutterEventChannel?
    private var eventSink: FlutterEventSink?
    private var dataTimer: Timer?

    private override init() {
        super.init()
    }

    /// 设置EventChannel
    func setupEventChannel(messenger: FlutterBinaryMessenger) {
        eventChannel = FlutterEventChannel(name: "data_event_channel", binaryMessenger: messenger)
        eventChannel?.setStreamHandler(self)
        print("✅ 数据事件EventChannel设置完成")
    }

    /// 开始模拟持续数据传递
    func startDataStream() {
        stopDataStream() // 先停止之前的定时器

        // 创建定时器，每3秒发送一次数据
        dataTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { [weak self] _ in
            self?.sendDataToFlutter()
        }

        print("🚀 开始模拟持续数据传递...")
    }

    /// 停止数据流
    func stopDataStream() {
        dataTimer?.invalidate()
        dataTimer = nil
        print("⏹️ 停止数据流")
    }

    /// 发送数据到Flutter
    private func sendDataToFlutter() {
        guard let eventSink = eventSink else {
            print("⚠️ EventSink未设置，无法发送数据")
            return
        }

        // 只保留2个常用的数据类型
        let dataTypes = ["location_update", "battery_status"]
        let randomType = dataTypes.randomElement() ?? "location_update"
        let timestamp = Date().timeIntervalSince1970

        let data: [String: Any] = [
            "type": randomType,
            "timestamp": timestamp,
            "data": _generateMockData(for: randomType),
            "message": "iOS端持续发送的数据 - \(randomType)"
        ]

        DispatchQueue.main.async {
            eventSink(data)
            print("📱 [EventChannel] 发送数据: \(data)")
        }
    }

    /// 生成模拟数据
    private func _generateMockData(for type: String) -> [String: Any] {
        switch type {
        case "location_update":
            return [
                "latitude": Double.random(in: 22.0...23.0),
                "longitude": Double.random(in: 113.0...114.0),
                "accuracy": Double.random(in: 5...50)
            ]
        case "battery_status":
            return [
                "level": Double.random(in: 0.1...1.0),
                "is_charging": Bool.random(),
                "temperature": Double.random(in: 20...40)
            ]
        default:
            return [:]
        }
    }

    /// 手动发送一次数据
    func sendManualData(_ data: [String: Any]) {
        guard let eventSink = eventSink else {
            print("⚠️ EventSink未设置，无法发送数据")
            return
        }

        let enhancedData: [String: Any] = [
            "type": "manual",
            "timestamp": Date().timeIntervalSince1970,
            "data": data,
            "message": "iOS端手动发送的数据"
        ]

        DispatchQueue.main.async {
            eventSink(enhancedData)
            print("📱 [EventChannel] 手动发送数据: \(enhancedData)")
        }
    }
}

// MARK: - FlutterStreamHandler 协议实现
extension DataEventChannel: FlutterStreamHandler {
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        print("📱 [EventChannel] Flutter开始监听数据流")
        eventSink = events
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        print("📱 [EventChannel] Flutter停止监听数据流")
        eventSink = nil
        return nil
    }
}
